//
//  UserInfoModel.swift
//  Exchange
//
//  Created by rui on 2018/6/5.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class UserInfoViewModel: BaseViewModel {
    
    var image: UIImage = #imageLiteral(resourceName: "login_icon")
    
    var imageAdress: String = ""
    
    var imageUrl: String = ""
    
    private lazy var portraitApi: PortraitRequest = {
        let portrait = PortraitRequest()
        portrait.dataReformer = self
        portrait.paramSource = self
        portrait.delegate = self
        return portrait
    }()
    
    private lazy var generateIconApi: GenerateIconRequest = {
        let portrait = GenerateIconRequest()
        portrait.dataReformer = self
        portrait.paramSource = self
        portrait.delegate = self
        return portrait
    }()
    
    ///生成头像地址
    func generateIconAdress(image: UIImage) {
        self.image = image
        self.generateIconApi.loadData()
    }
    
    ///头像地址入库
    func updatePortrait(image: String) {
        self.imageAdress = image
        self.portraitApi.loadData()
    }
    
}

extension UserInfoViewModel: RequestCallBack,RequestDataReformer,RequestParamSource {
    
    func reform(_ request: BaseRequest, _ data: [String : Any]?) {
        if let _ = request as? GenerateIconRequest {
            if let d = data?["data"] as? [String:Any], let imageAdress = d["relativePath"] as? String,let imageUrl = d["absolutePath"] as? String {
                self.imageUrl = imageUrl
                self.updatePortrait(image: imageAdress)
            }else {
                self.response?(ResponseState.mine_portrait,false, nil)
            }
        }else if let _ = request as? PortraitRequest {
            AppInfo.default.portrait = imageUrl
            AppInfo.default.write()
            self.response?(ResponseState.mine_portrait,true, nil)
        }
    }
    
    func requestDidSucess(_ request: BaseRequest) {
        
    }
    
    func requestDidFail(_ request: BaseRequest) {
        if let _ = request as? GenerateIconRequest {
             self.response?(ResponseState.mine_portrait,false, nil)
        }else if let _ = request as? PortraitRequest {
            self.response?(ResponseState.mine_portrait,false, nil)
        }
    }
    
    func requestParams(_ request: BaseRequest) -> [String : Any]? {
        var pramas: [String:Any] = [:]
        if let _ = request as? GenerateIconRequest {
            let img = image.compressToSize(CGSize(width: 160, height: 160))
            let imageData = UIImageJPEGRepresentation(img, 1.0)!
            let file = File(fileData: imageData, fileName: "myPortrait.jpeg", fileMIMEType: "image/jpeg")
            pramas.updateValue([file], forKey: "file")
            pramas.updateValue("portrait", forKey: "type")
        }else if let _ = request as? PortraitRequest {
            pramas.updateValue(imageAdress, forKey: "portrait")
        }
        return pramas
    }
    
}
